import re
from collections import OrderedDict
from django import template
from django.conf import settings
from django.urls import reverse
from django.http import QueryDict


register = template.Library()


@register.inclusion_tag('rbac/my_menu.html')
def my_menu(request):
    menu_dict = request.session.get(settings.SESSION_MENU_KEY)
    key_list = sorted(menu_dict)
    ordered_dict = OrderedDict()
    flag = False

    for key in key_list:
        val = menu_dict[key]

        for c in val['children']:
            tmp = '^%s$' % c['url']
            if re.match(tmp, request.path_info):
                c['class'] = 'active'
                flag = True
                break

        if flag:
            break

    for key in key_list:
        val = menu_dict[key]
        ordered_dict[key] = val

    return {'menu_dict': ordered_dict}


@register.inclusion_tag('rbac/my_route.html')
def my_route(request):
    return {'route_list': request.route_list}


@register.filter
def has_permission(request, name):
    if name in request.session.get(settings.SESSION_PERMISSION_KEY):
        return True


@register.simple_tag
def custom_url(request, name, *args, **kwargs):
    basic_url = reverse(name, args=args, kwargs=kwargs)
    if not request.GET:  # 当前url中无参数
        return basic_url
    else:
        q_dict = QueryDict(mutable=True)
        q_dict['_addi'] = request.GET.urlencode()

        return '%s?%s' % (basic_url, q_dict.urlencode())
